import java.lang.Thread;
import java.lang.Runtime;
import java.io.*;

public class CounterLauncher extends Thread{
	private static Process[] counter = null;
	private static Runtime rt = Runtime.getRuntime();
	
	private int counterNumber;
	
	
	public CounterLauncher(int counterNumber){
		this.counterNumber = counterNumber;
	}
	
	public void run(){
		try {
			counter[counterNumber] = rt.exec("xterm -e java Counter & /bin/bash");
			System.out.println("Counter " + (counterNumber+1) + " launched.");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public static void main(String[] args) {
		int nb = 0;
		try {
			nb = Integer.valueOf(args[0]);
		} catch (Exception exc) {
			System.err.println("CounterLauncher <nbProcess>");
			exc.printStackTrace();
			System.exit(0);
		}

		Process rmireg = null;
		Process server = null;
		try {
			rmireg = rt.exec("rmiregistry");
			Thread.sleep(3000);
			server = rt.exec("java Server");
			Thread.sleep(1000);

			System.out.println("Initialization.");
			Client.init();
			SharedObject c = Client.lookup("CPT");
			if(c == null) {
				c = Client.create(new Integer(0));
				Client.register("CPT", c);
			}
			System.out.println("System initialized.");

			counter = new Process[nb];
			int prcs = 0;
			for(prcs=0; prcs < nb ; prcs++) {
				(new CounterLauncher(prcs)).start();
			}
			sleep(prcs*500);	//needed in order to let the processes put their respective counter[prcs] properly.

			for(int i = 0 ; i < nb ; i++) {
				System.out.println("Counter : " + (i+1));
				BufferedReader br = new BufferedReader(new InputStreamReader(counter[i].getInputStream()));
				String s = null;
				while((s = br.readLine()) != null) {
					System.out.println(s);
				}

				br = new BufferedReader(new InputStreamReader(counter[i].getErrorStream()));
				while((s = br.readLine()) != null) {
					System.err.println(s);
				}
			}

			c.lock_read();
			System.out.println("Final value : " + ((Integer)(c.obj)).intValue());
			c.unlock();

			for(int i = 0 ; i < nb ; i++) {
				System.out.print("Waiting for counter " + (i+1) + " to finish...");
				//counter[i].waitFor();
				counter[i].destroy();
				System.out.println("OK !");
			}

			/*
			System.out.println("Server");
			BufferedReader br = new BufferedReader(new InputStreamReader(server.getInputStream()));
			String s = null;
			while((s = br.readLine()) != null) {
				System.out.println(s);
			}
			br = new BufferedReader(new InputStreamReader(server.getErrorStream()));
			s = null;
			while((s = br.readLine()) != null) {
				System.err.println(s);
			}
			//*/

		} catch(Exception exc) {
			exc.printStackTrace();
		} finally {
			rmireg.destroy();
			server.destroy();
			for(int i = 0 ; i < nb ; i++) {
				counter[i].destroy();
			}

		}

		System.exit(0);
	}

}
